package com.michale.admin.controller.common;

import com.michale.common.annotation.Anonymous;
import com.michale.common.annotation.NotRepeatSubmit;
import com.michale.common.constants.CommonConstant;
import com.michale.common.constants.RedisCacheConstant;
import com.michale.common.properties.MichaleProperties;
import com.michale.common.result.AjaxResult;
import com.michale.common.utils.redis.RedisUtils;
import com.michale.common.utils.sign.Base64Utils;
import com.michale.common.utils.uuid.IdUtils;
import com.michale.framework.config.captcha.CaptchaUtils;
import com.michale.system.service.ConfigService;
import com.michale.system.vo.captcha.CaptchaVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Michale
 * @apiNote 验证码管理
 */
@Slf4j
@Api(tags = "验证码管理")
@RestController("/dev-api")
public class CaptchaController {

    @Resource
    private RedisUtils redisUtils;
    @Resource
    private CaptchaUtils captchaUtils;
    @Resource
    private ConfigService configService;

    /**
     * 生成验证码
     */
    @NotRepeatSubmit
    @Anonymous
    @GetMapping("/captchaImage")
    public CaptchaVo getCode(HttpServletResponse response) throws Exception {
        boolean registerEnabled = configService.selectRegister();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = RedisCacheConstant.CAPTCHA_CODE_KEY + uuid;

        String capStr;
        String code;
        BufferedImage image;

        //获取验证码类型
        String captchaType = MichaleProperties.getCaptchaType();
        // 生成验证码
        Map<String, Object> map = captchaUtils.creatCaptcha(captchaType);
        image = (BufferedImage) map.get("image");
        capStr = (String) map.get("capStr");
        code = (String) map.get("code");

        redisUtils.setCacheObject(verifyKey, code, CommonConstant.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        ImageIO.write(image, "jpg", os);
        AjaxResult ajax = AjaxResult.success("验证码");
        CaptchaVo captchaVo = new CaptchaVo();
        captchaVo.setImg(Base64Utils.encode(os.toByteArray()));
        captchaVo.setUuid(uuid);
        captchaVo.setCapStr(capStr);
        captchaVo.setCaptchaEnabled(captchaEnabled);
        captchaVo.setRegisterEnabled(registerEnabled);
        return captchaVo;

    }
}
